//
//  ScanViewController.m
//  WorkerNews
//
//  Created by JiaCong Zhu on 2019/1/21.
//  Copyright © 2019 XiMu. All rights reserved.
//

#import "ScanViewController.h"
#import "ScanMaskView.h"
#import <AVFoundation/AVFoundation.h>
#import "NetworkAddress.h"
#import <Masonry/Masonry.h>
#import "UIColor+EX.h"

/***  屏幕宽高比例 */
#define SCALE(s)                          ((s) / 375.0 * kScreenWidth)

/** 创建UIimage*/
#define Image(s) [UIImage imageNamed:s]

@interface ScanViewController () <AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) UIButton  *cancelButton;
@property (nonatomic, strong) UILabel   *titleLabel;
@property (nonatomic, strong) ScanMaskView  *maskView;
@property (nonatomic, strong) UIView    *cameraView;
@property (nonatomic, strong) UIImageView *scanLineView;

@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic, assign) BOOL isScaning;
@end

@implementation ScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self p_createSubViews];
    self.isScaning = NO;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self startReading];
    self.scanLineView.frame = CGRectMake(kScreenWidth / 2 - SCALE(251 / 2.0), kScreenHeight / 2 - SCALE(240 / 2.0), SCALE(251), SCALE(3));
    [UIView beginAnimations:@"scan" context:nil];
    [UIView setAnimationDuration:1.5f];
    [UIView setAnimationRepeatCount:MAXFLOAT];
    [UIView setAnimationRepeatAutoreverses:YES];
    self.scanLineView.frame = CGRectMake(kScreenWidth / 2 - SCALE(251 / 2.0), kScreenHeight / 2 + SCALE(240 / 2.0) - SCALE(3), SCALE(251), SCALE(3));
    [UIView commitAnimations];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self stopReading];
}

// 状态栏颜色控制
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)p_createSubViews {
    self.view.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.cameraView];
    [self.view addSubview:self.maskView];
    [self.view addSubview:self.cancelButton];
    [self.view addSubview:self.titleLabel];
    [self.maskView addSubview:self.scanLineView];
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(self.view).insets(UIEdgeInsetsMake(SCALE(18) + kStatusBarHeight, SCALE(18), 0, 0));
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.cancelButton);
        make.centerX.mas_equalTo(self.view);
    }];
    [self.cameraView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    [self.maskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

-(BOOL)startReading {
    //将图层添加到预览view的图层上
    [self.cameraView.layer addSublayer:self.videoPreviewLayer];
    //开始扫描
    [self.captureSession startRunning];
    return YES;
}

-(void)stopReading {
    [self.captureSession stopRunning];
    self.captureSession = nil;
    [self.videoPreviewLayer removeFromSuperlayer];
    self.videoPreviewLayer = nil;
    self.isScaning = NO;
}

#pragma mark - Lazy Init
- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelButton setTitleColor:[UIColor colorWithHexString:@"33B87C"] forState:UIControlStateNormal];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_cancelButton addTarget:self action:@selector(didBack) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}

- (UILabel *)titleLabel {
    if(!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:17];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.text = @"二维码";
    }
    return _titleLabel;
}

- (ScanMaskView *)maskView {
    if (!_maskView) {
        _maskView = [[ScanMaskView alloc] init];
    }
    return _maskView;
}

- (UIView *)cameraView {
    if (!_cameraView) {
        _cameraView = [[UIView alloc] init];
        _cameraView.backgroundColor = [UIColor clearColor];
    }
    return _cameraView;
}

- (UIImageView *)scanLineView {
    if (!_scanLineView) {
        _scanLineView = [[UIImageView alloc] initWithImage:Image(@"icon_scan_line")];
    }
    return _scanLineView;
}

- (AVCaptureSession *)captureSession {
    if (!_captureSession) {
        NSError *error;
        //1.初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        //2.用captureDevice创建输入流
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
        if (!input) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *goSetting = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if([[UIApplication sharedApplication] canOpenURL:url]) {
                        if (@available(iOS 10.0, *)) {
                            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                        } else {
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    }
                }];
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"需要获取摄像头访问权限" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:cancel];
                [alert addAction:goSetting];
                [self presentViewController:alert animated:YES completion:nil];
            });
            return nil;
        }
        
        //3.创建媒体数据输出流
        AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
        
        //4.实例化捕捉会话
        _captureSession = [[AVCaptureSession alloc] init];
        
        //4.1.将输入流添加到会话
        [_captureSession addInput:input];
        
        //4.2.将媒体输出流添加到会话中
        [_captureSession addOutput:captureMetadataOutput];
        
        //4.3.设置为高清
        [_captureSession setSessionPreset:AVCaptureSessionPresetHigh];
        //5.创建串行队列，并加媒体输出流添加到队列当中
        dispatch_queue_t dispatchQueue;
        dispatchQueue = dispatch_queue_create("AVCaptureMetadataOutputObjectsDelegate", NULL);
        //5.1.设置代理
        [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
        //5.2.设置输出媒体数据类型为QRCode
        [captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]];
        //10.设置扫描范围
        captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
        
    }
    return _captureSession;
}

- (AVCaptureVideoPreviewLayer *)videoPreviewLayer {
    if (!_videoPreviewLayer) {
        //6.实例化预览图层
        _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
        
        //7.设置预览图层填充方式
        [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        
        //8.设置图层的frame
        [_videoPreviewLayer setFrame:[UIScreen mainScreen].bounds];
    }
    return _videoPreviewLayer;
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (self.isScaning) {
        return;
    }
    self.isScaning = YES;
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeEAN13Code] || [[metadataObj type] isEqualToString:AVMetadataObjectTypeEAN8Code] || [[metadataObj type] isEqualToString:AVMetadataObjectTypeCode128Code]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *qrCodeString = metadataObj.stringValue;
                
                [self dismissViewControllerAnimated:YES completion:^{
                    if ([self.delegate respondsToSelector:@selector(getQrCodeString:)]) {
                        [self.delegate getQrCodeString:qrCodeString];
                        
                    }
                }];
                
            });
        } else {
            self.isScaning = NO;
        }
    } else {
        self.isScaning = NO;
    }
}
@end
